package com.yonyou.cyxdms.sysAuth.service.controller.manage.company;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoleilu.hutool.util.StrUtil;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.dto.ComOrganizationDTO;
import com.yonyou.cyxdms.sysAuth.service.entity.CompanyPO;
import com.yonyou.cyxdms.sysAuth.service.entity.UserPO;
import com.yonyou.cyxdms.sysAuth.service.mapper.ComOrganizationMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.UserMapper;
import com.yonyou.cyxdms.sysAuth.service.service.dealerchannel.DealerInfoService;
import com.yonyou.cyxdms.sysAuth.service.service.manage.company.CompanyOrgMaintenanceService;
import com.yonyou.cyxdms.sysAuth.service.service.manage.company.CompanyOrgMaintenanceServiceImpl;
import com.yonyou.cyxdms.sysAuth.service.vo.companyorg.*;
import com.yonyou.cyxdms.sysmanage.client.vo.company.CompanyDealerAscVO;
import com.yonyou.cyxdms.sysmanage.client.vo.company.CompanyOrgVO;
import com.yonyou.cyxdms.sysmanage.client.vo.company.CompanyVO;
import com.yonyou.cyxdms.sysmanage.client.vo.employee.LoginUserVO;
import io.swagger.annotations.*;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 公司组织维护控制类
 *
 * @author renwd
 * @since 2019/7/8
 */

@Api(value = "CompanyOrgMaintenanceController", tags = {"公司组织维护控制类"})
@RestController
@RequestMapping("/company/org")
public class CompanyOrgMaintenanceController {

    @Autowired
    private CompanyOrgMaintenanceService companyOrgMaintenanceService;

    @Autowired
    private DealerInfoService dealerInfoService;

    @Autowired
    private ComOrganizationMapper organizationMapper;

    @Autowired
    public RedissonClient redissonClient;

    @Autowired
    private UserMapper userMapper;

    private static final Logger logger = LoggerFactory.getLogger(CompanyOrgMaintenanceServiceImpl.class);

    /**
     * 分页查询公司组织
     *
     * @param current
     * @param size
     * @param param
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.yonyou.cyxdms.sysAuth.service.vo.companyorg.CompanyOrgPageVO>
     * @author renwd
     * @since 2019/7/8
     */
    @ApiOperation(value = "分页查询公司组织")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @GetMapping
    public IPage<CompanyOrgPageVO> pageCompanyOrg(@RequestParam("pageNum") Long current, @RequestParam("limit") Long size, @RequestParam Map<String, Object> param) {
        Page<CompanyOrgPageVO> page = new Page(current, size);
        return companyOrgMaintenanceService.pageCompanyOrg(page, param);
    }

    /**
     * 获取树状图
     *
     * @param
     * @return java.util.List<com.yonyou.cyxdms.sysAuth.service.vo.companyorg.CompanyOrgMaintenanceTreeVO>
     * @author renwd
     * @since 2019/7/8
     */
    @ApiOperation(value = "员工界面获取树状图")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @RequestMapping(value = "/tree", method = RequestMethod.GET)
    public List<CompanyOrgMaintenanceTreeVO> getOrgs() {
        return companyOrgMaintenanceService.getComOrgTree();
    }

    /**
     * 获取树状图
     *
     * @param
     * @return java.util.List<com.yonyou.cyxdms.sysAuth.service.vo.companyorg.CompanyOrgMaintenanceTreeVO>
     * @author wst
     * @since 2021/12/2
     */
    @ApiOperation(value = "员工界面获取树状图")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @RequestMapping(value = "/drlTree", method = RequestMethod.GET)
    public List<CompanyOrgMaintenanceTreeVO> getDelOrgs() {
        return companyOrgMaintenanceService.getComOrgTreeDrl();
    }

    /**
     * 获取树状图
     *
     * @param
     * @return java.util.List<com.yonyou.cyxdms.sysAuth.service.vo.companyorg.CompanyOrgMaintenanceTreeVO>
     * @author zw
     * @since 2020/7/16
     */
    @ApiOperation(value = "员工界面获取树状图")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @RequestMapping(value = "/treeDistinct", method = RequestMethod.GET)
    public List<CompanyOrgMaintenanceTreeVO> getOrgsDistinct() {
        return companyOrgMaintenanceService.getComOrgTreeDistinct();
    }

    /**
     * 获取车厂所有组织
     *
     * @param
     * @return java.util.List<com.yonyou.cyxdms.sysmanage.client.vo.company.CompanyOrgVO>
     * @author zys
     * @since 2020/2/5
     */
    @ApiOperation(value = "获取车厂所有组织")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @RequestMapping(value = "/allTree", method = RequestMethod.GET)
    public List<CompanyOrgVO> getOrgsNoCompanyId() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return organizationMapper.getComOrgAllTree(loginInfoDto.getAppId());
    }

    /**
     * 新增组织
     *
     * @param orgDto
     * @return java.lang.Integer
     * @author renwd
     * @since 2019/7/8
     */
    @ApiOperation(value = "新增组织")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @PostMapping
    public Integer addOrg(@RequestBody ComOrganizationDTO orgDto) {
        return companyOrgMaintenanceService.addOrg(orgDto);
    }

    /**
     * 修改部门
     *
     * @param ids
     * @param orgDto
     * @return void
     * @author renwd
     * @since 2019/7/8
     */
    @ApiOperation(value = "修改部门")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @PutMapping("/{id}")
    public void modifyOrg(@PathVariable("id") String ids, @RequestBody ComOrganizationDTO orgDto) {
        companyOrgMaintenanceService.modifyComOrg(ids, orgDto);
    }


    /**
     * 新增接口，保存公司表、经销商表、服务站表、组织表、组织关系表、
     * 人员表、用户表、员工表、职位表、角色表、app版本表、
     * 用户菜单表他的两个子表、员工菜单表以及他的两个子表。
     *
     * @author 李贺
     * @since 2019/9/10
     */
    @ApiOperation(value = "新增公司")
    @PutMapping("/addDealerCompany")
    public CompanyDealerAscVO addDealerCompany(@RequestBody CompanyDealerAscVO companyDealerAscVO
    ) {
        return companyOrgMaintenanceService.addDealerCompany(companyDealerAscVO);
    }

    /**
     * 新增多个公司
     *
     * @author 李贺
     * @since 2019/12/2
     */
    @ApiOperation(value = "新增多个公司")
    @PostMapping("/addDealerCompanyList")
    public List<CompanyDealerAscVO> addDealerCompanyList(@RequestBody List<CompanyDealerAscVO> companyDealerAscVOList
    ) {
        return companyOrgMaintenanceService.addDealerCompanyList(companyDealerAscVOList);
    }

    /**
     * 更新接口，更新公司表、经销商表、服务站表
     *
     * @author 李贺
     * @since 2019/9/12
     */
    @ApiOperation(value = "更新公司")
    @PostMapping("/updateDealerCompany")
    public CompanyDealerAscVO updateDealerCompany(@RequestBody CompanyDealerAscVO companyDealerAscVO) {
        LoginUserVO loginUserVO = companyDealerAscVO.getLoginUserVO();
        if (loginUserVO == null) {
            throw new ServiceBizException("loginUserVO不能为空");
        }
        loginUserVO.setUserId(null);
        String appId = loginUserVO.getAppId();
        if (StringUtils.isNullOrEmpty(appId)) {
            throw new ServiceBizException("loginUserVO中appId不能为空");
        }
        String oldUserCode = loginUserVO.getOldUserCode();
        if (StringUtils.isNullOrEmpty(oldUserCode)) {
            throw new ServiceBizException("loginUserVO中oldUserCode不能为空");
        }
        LambdaQueryWrapper<UserPO> lambdaQueryWrapper = new QueryWrapper<UserPO>().lambda();
        lambdaQueryWrapper.eq(UserPO::getUserCode, oldUserCode)
                .eq(UserPO::getAppId, appId);
        UserPO userpo = userMapper.selectOne(lambdaQueryWrapper);
        if (!StringUtils.isNullOrEmpty(userpo.getRegId())) {
            String messageFormat = StrUtil.format("cyxdms.sysManager.login.regId.lock.{}",
                    userpo.getRegId(), userpo.getRegId());
            RLock lock = redissonClient.getLock(messageFormat);
            try {
                boolean res = lock.tryLock(0, 300, TimeUnit.SECONDS);
                if (!res) {
                    throw new ServiceBizException("接口正在被调用,发生并发");
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage(), e);
            } finally {
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }
        return companyOrgMaintenanceService.updateCompany(companyDealerAscVO);

    }


    /**
     * 分页查询数据
     *
     * @param 查询条件
     * @return com.baomidou.mybatisplus.core.metadata.IPage 分页对象
     * @author zhangxianchao
     * @since 2018-09-13
     */
    @ApiOperation(value = "查询经销商")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @RequestMapping(value = "/getDealerByParam", method = RequestMethod.POST)
    public IPage<DealerPageVO> getDealerByParam(@RequestBody GetDealerVO getDealerVO) {
        Page<DealerPageVO> page = new Page(getDealerVO.getCurrentPage(), getDealerVO.getPageSize());
        return dealerInfoService.getDealerByParam(page, getDealerVO.getDealerName());
    }

    /**
     * 分页查询数据
     *
     * @param 查询条件
     * @return com.baomidou.mybatisplus.core.metadata.IPage 分页对象
     * @author zhangxianchao
     * @since 2018-09-13
     */
    @ApiOperation(value = "查询经销商")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    @RequestMapping(value = "/getDealerByParam", method = RequestMethod.GET)
    public IPage<DealerPageVO> getDealerByParam(
            @RequestParam("currentPage") int currentPage,
            @RequestParam("pageSize") int pageSize,
            @ApiParam(name = "dealerName", value = "公司名称", required = false) @RequestParam(value = "dealerName", required = false, defaultValue = "") String dealerName) {
        Page<DealerPageVO> page = new Page(currentPage, pageSize);
        return dealerInfoService.getDealerByParam(page, dealerName);
    }

    /**
     * 根据公司Id,获得公司信息
     * <p>
     * *@author 李贺
     *
     * @since 2019/10/18
     */
    @ApiOperation(value = "根据公司Id,获得公司信息")
    @GetMapping("/getCompany")
    public CompanyVO getCompany(@ApiParam(name = "companyId", value = "companyId") @RequestParam(value = "companyId") Long companyId) {
        return companyOrgMaintenanceService.getCompany(companyId);
    }


    /**
     * 车厂通过组织id（大区小区类型的组织）获取本车厂下对应的经销商
     *
     * @param orgId
     * @param:
     * @return: 车厂通过组织id（大区小区类型的组织）获取本车厂下对应的经销商
     * @auther: 马邢健
     * @since: 2019/10/31
     */
    @ApiOperation(value = "车厂通过组织id（大区小区类型的组织）获取本车厂下对应的经销商")
    @GetMapping("/getDealerBySaleArea")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    public List<DealerOrgAreaVO> getDealerBySaleArea(@ApiParam(name = "orgId", value = "组织ID", required = false) @RequestParam(required = false, defaultValue = "") String orgId,
                                                     @ApiParam(name = "dealerCode", value = "经销商编号", required = false) @RequestParam(required = false, defaultValue = "") String dealerCode,
                                                     @ApiParam(name = "dealerName", value = "经销商名称", required = false) @RequestParam(required = false, defaultValue = "") String dealerName) {
        return dealerInfoService.getDealerBySaleArea(orgId, dealerCode, dealerName);
    }

    /**
     * 获得当前车厂 的合并 售后规则
     *
     * @return: 获得当前车厂 的合并 售后规则
     * @auther: 李贺
     * @since: 2019/11/4
     */
    @ApiOperation(value = "车厂通过组织id（大区小区类型的组织）获取本车厂下对应的经销商")
    @GetMapping("/getMerge")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    public MergeVO getMerge() {
        return companyOrgMaintenanceService.getMerge();
    }

    /**
     * 获得当前车厂的信息
     *
     * @return: 获得当前车厂的信息
     * @auther: 李贺
     * @since: 2019/11/26
     */
    @ApiOperation(value = "获得当前车厂的信息")
    @GetMapping("/factoryCompany")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "userId", name = "userId", required = true, dataType = "string", paramType = "header")
    })
    public CompanyVO factoryCompany() {
        return companyOrgMaintenanceService.factoryCompany();
    }

    /**
     * 根据公司统一社会信息用代码匹配SAP客户编号（公司编号）
     *
     * *@author 饶强
     * @since 2020/9/20
     */
    @ApiOperation(value = "根据公司统一社会信息用代码匹配SAP客户编号")
    @GetMapping("/matchingSapCustomerNo")
    public List<String> matchingSapCustomerNo(@ApiParam(name = "credentialsNo", value = "credentialsNo") @RequestParam(value = "credentialsNo") String credentialsNo) {
        return companyOrgMaintenanceService.matchingSapCustomerNo(credentialsNo);
    }

}
